package com.example.yunifang.fragment;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
import java.util.Random;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import cn.sharesdk.framework.authorize.ResizeLayout;

import com.alipay.sdk.app.PayTask;
import com.alipay.sdk.pay.demo.H5PayDemoActivity;
import com.alipay.sdk.pay.demo.PayResult;
import com.alipay.sdk.pay.demo.SignUtils;
import com.example.yunifang.DengluActivity;
import com.example.yunifang.R;
import com.example.yunifang.XiangQingActivity;
import com.example.yunifang.ZhuActivity;
import com.example.yunifang.adapter.Frgament3Adapter;
import com.example.yunifang.bean.GouWuCheBean;
import com.example.yunifang.dao.GouWuCheDao;
import com.example.yunifang.myview.MyListView;

public class Fragment3 extends Fragment implements OnClickListener {
	private RelativeLayout layout;
	private LinearLayout fragment_text_tv1;
	private Context context;
	private MyListView lv;
	public static TextView fragment3_zongji;
	public static CheckBox fragment3_box;
	private Frgament3Adapter adapter;
	private TextView fragment3_title;
	private TextView fragment3_bianji;
	public static double sum;
	public boolean flag = true;
	private TextView fragment3_shanchu;
	//int i=Frgament3Adapter.i;
	private GouWuCheDao dao;
	private ArrayList<GouWuCheBean> data=new ArrayList<GouWuCheBean>();
	private RadioButton button;
	// 商户PID
		public static final String PARTNER = "2088901305856832";
		// 商户收款账号
		public static final String SELLER = "8@qdbaiu.com";
		// 商户私钥，pkcs8格式
		public static final String RSA_PRIVATE = "MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAM/KCxg/OIj6er2GEig0DOkHqBSzEPHGigMbTXP1k2nrxEHeE59xOOuyovQH/A1LgbuVKyOac3uAN4GXIBEoozRVzDhu5dobeNm48BPcpYSAfvN3K/5GLacvJeENqsiBx8KufM/9inlHaDRQV7WhX1Oe2ckat1EkdHwxxQgc36NhAgMBAAECgYEAwn3sWpq6cUR65LD8h9MIjopTImTlpFjgz72bhsHDZK6A+eJDXcddrwh7DI34t/0IBqu+QEoOc/f0fIEXS9hMwTvFY59XG7M8M6SdeaAbemrGmZ1IdD6YDmpbQFHn2ishaYF0YDZIkBS3WLDFrtk/efaarBCpGAVXeEiVQE4LewECQQD5W1rpkq+dHDRzzdtdi1bJ479wun5CfmVDVb2CJH7Iz0t8zyp/iEVV2QELnxZMphmoSzKaLXutTTj2OImpzCtRAkEA1VMxG6nQq9NkU51H1+I3mlUXRZ0XeFA1GFJ7xWpNRAVhEWlDz2zy9v/gX+RFpNC3f5uznycas70Xp78ew43TEQJAZFFqi9mlqTF1sLk67bFnIyXrGPEOZrXvC13tNfR0xVkQZ4/46wHp0xXQo9pG4GNaoyhNnVV7EkelCPnJ+HPZYQJAQh6T9QgQZoGR8hyovPAf3dUL7oa/VIo/urcuJ8VIB5JHQNdIrk0NjaNHj1E4iNosVgATj3vWWel9IIArb99QkQJAKvfm78lwnImtg5IM604hdn/Wu1XF8tpxsKLWcnfchMr0bM9rCmKmhAY+wdmqSyPZRiNb1QaaaDTqJxLy6AnQ+Q==";
		// 支付宝公钥
		public static final String RSA_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCd6rV3vOE578e6VlGEakZpPdsX2QmGdIfi/yHe cg1CIEWzX9wn2LNFGtu1EzYQyKACG/RKeog0pUJEVGfBG30zFdNY2YocYJNdPtADqhJbS0GJm7f8 1vRiLKtOwKjdiz9oMEwxhc/5fysfMbercidRmlCDPU9BNL1UPb9bAx25JwIDAQAB";
		private static final int SDK_PAY_FLAG = 1;

		@SuppressLint("HandlerLeak")
		private Handler mHandler = new Handler() {
			@SuppressWarnings("unused")
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case SDK_PAY_FLAG: {
					PayResult payResult = new PayResult((String) msg.obj);
					/**
					 * 同步返回的结果必须放置到服务端进行验证（验证的规则请看https://doc.open.alipay.com/doc2/
					 * detail.htm?spm=0.0.0.0.xdvAU6&treeId=59&articleId=103665&
					 * docType=1) 建议商户依赖异步通知
					 */
					String resultInfo = payResult.getResult();// 同步返回需要验证的信息

					String resultStatus = payResult.getResultStatus();
					// 判断resultStatus 为“9000”则代表支付成功，具体状态码代表含义可参考接口文档
					if (TextUtils.equals(resultStatus, "9000")) {
						Toast.makeText(getActivity(), "支付成功", Toast.LENGTH_SHORT).show();
					} else {
						// 判断resultStatus 为非"9000"则代表可能支付失败
						// "8000"代表支付结果因为支付渠道原因或者系统原因还在等待支付结果确认，最终交易是否成功以服务端异步通知为准（小概率状态）
						if (TextUtils.equals(resultStatus, "8000")) {
							Toast.makeText(getActivity(), "支付结果确认中", Toast.LENGTH_SHORT).show();

						} else {
							// 其他值就可以判断为支付失败，包括用户主动取消支付，或者系统返回的错误
							Toast.makeText(getActivity(), "支付失败", Toast.LENGTH_SHORT).show();

						}
					}
					break;
				}
				default:
					break;
				}
			};
		};


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		View view = View.inflate(getActivity(), R.layout.fragment3, null);
		String name=getActivity().getIntent().getStringExtra("userImg");
		if(name!=null){
			init(view);
			adapter.notifyDataSetChanged();
		}else{
			Intent intent=new Intent(getActivity(),DengluActivity.class);
			startActivity(intent);
		}
		return view;
	}

	public void init(View view) {
		dao = new GouWuCheDao(getActivity());
		ArrayList<GouWuCheBean> data2 = dao.quaryAll();
		data.clear();
		data.addAll(data2);
		fragment3_zongji = (TextView) view.findViewById(R.id.fragment3_zongji);
		fragment3_shanchu = (TextView) view
				.findViewById(R.id.fragment3_shanchu);
		fragment3_box = (CheckBox) view.findViewById(R.id.fragment3_box);
		layout = (RelativeLayout) view.findViewById(R.id.include_no_wifi3);
		fragment_text_tv1 = (LinearLayout) view.findViewById(R.id.tv_2_3);
		context = getActivity();
		fragment3_title = (TextView) view.findViewById(R.id.fragment3_title);
		button = (RadioButton) view.findViewById(R.id.no_wifi_btn);
		fragment3_bianji = (TextView) view.findViewById(R.id.fragment3_bianji);
		fragment3_bianji.setText("编辑");
		fragment3_bianji.setOnClickListener(this);
		getWe();
		button.setOnClickListener(this);
		fragment3_shanchu.setOnClickListener(this);
		lv = (MyListView) view.findViewById(R.id.fragment3_lv);
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				String id=data.get(arg2).getShop_id();
				int ids=Integer.parseInt(id);
				Intent intent=new Intent(getActivity(),XiangQingActivity.class);
				intent.putExtra("id", ids);
				startActivity(intent);
			}
		});
		adapter = new Frgament3Adapter(data, getActivity());
		adapter.notifyDataSetChanged();
		fragment3_title.setText("购物车(" + data.size() + ")");
		lv.setAdapter(adapter);
		fragment3_box.setOnClickListener(this);
	}

	public void getWe() {
		// TODO Auto-generated method stub
		if (isNetworkAvailable(context)) {
			Toast.makeText(context.getApplicationContext(), "当前网络可用", 0).show();
			fragment_text_tv1.setVisibility(View.VISIBLE);
			layout.setVisibility(View.INVISIBLE);
		} else {
			Toast.makeText(context.getApplicationContext(), "当前网络不可用", 0)
					.show();
			fragment_text_tv1.setVisibility(View.INVISIBLE);
			layout.setVisibility(View.VISIBLE);
		}
	}

	private boolean isNetworkAvailable(Context zhuActivity) {
		// TODO Auto-generated method stub
		Context context = zhuActivity.getApplicationContext();
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);

		if (connectivityManager == null) {
			return false;
		} else {
			NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

			if (networkInfo != null && networkInfo.length > 0) {
				for (int i = 0; i < networkInfo.length; i++) {
					// System.out.println(i + "===״̬===" +
					// networkInfo[i].getState());
					// System.out.println(i + "===����===" +
					// networkInfo[i].getTypeName());
					if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED) {
						return true;
					}
				}
			}
		}
		return false;
	}
	public void bianji() {
		fragment3_zongji.setVisibility(View.GONE);
		fragment3_bianji.setText("完成");
		fragment3_shanchu.setText("删除");
		if(adapter.getSelect().contains(true)){
			for(int i = 0;i<adapter.getSelect().size();i++){
				adapter.getSelect().set(i,false);
			}
			fragment3_box.setChecked(false);
		}
		adapter.showBtn(flag);
		flag = false;
	}
	public void wanCheng() {
		fragment3_zongji.setVisibility(View.VISIBLE);
		fragment3_bianji.setText("编辑");
		fragment3_shanchu.setText("结算");
		if(adapter.getSelect().contains(true)){
			for(int i = 0;i<adapter.getSelect().size();i++){
				adapter.getSelect().set(i,false);
			}
			fragment3_box.setChecked(false);
		}
		for(int i=0;i<adapter.getLink().size();i++){
			dao.update(adapter.getLink().get(i),data.get(i).getShop_id());
		}
		adapter.notifyDataSetChanged();
		ArrayList<GouWuCheBean> data2=dao.quaryAll();
		data.clear();
		data.addAll(data2);
		adapter=new Frgament3Adapter(data, getActivity());
		lv.setAdapter(adapter);
		fragment3_title.setText("购物车(" + data.size() + ")");
		//修改数量
		fragment3_box.setChecked(false);
		adapter.showBtn(flag);
		flag = true;
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.no_wifi_btn:
			getWe();
			break;
		case R.id.fragment3_bianji:
			if (flag == true) {
				bianji();
				adapter.notifyDataSetChanged();
			} else {
				wanCheng();
				adapter.notifyDataSetChanged();
			}
			adapter.notifyDataSetChanged();
			break;
		case R.id.fragment3_box:
			boolean flag1 = fragment3_box.isChecked();
			for (int i = 0; i < adapter.getSelect().size(); i++) {
				adapter.getSelect().set(i, flag1);
			}
			if(!fragment3_box.isChecked()){
				sum=0.00;
			}else{
				
				for (int i = 0; i < adapter.getSelect().size(); i++) {
					
					if (adapter.getSelect().get(i) == true) {
						
						sum = sum
								+ Float.valueOf(data.get(i).getNum()
										* data.get(i).getPrice() + "");
					} else if (adapter.getSelect().get(i) == false) {
						sum=0.00;
						sum = sum
								- Float.valueOf(data.get(i).getNum()
										* data.get(i).getPrice() + "");
					}
				}
			}
			
			adapter.sum = sum;
			adapter.notifyDataSetChanged();
			break;
		case R.id.fragment3_shanchu:
			//删除商品
			deleteGouwu();
			break;
		default:
			break;
		}
	}

	public void deleteGouwu() {
		if(flag == true){
			Toast.makeText(getActivity(), "结算", 0).show();
			pay();
		}else{
			if(adapter.getSelect().contains(true)){
				ArrayList<String> deleteData=new ArrayList<String>();
				for(int i=0;i<adapter.getSelect().size();i++){
					if(adapter.getSelect().get(i)==true){
						deleteData.add(data.get(i).getShop_id());
					}
				}
				dao.delete(deleteData);
				wanCheng();
			}
		}
	}
	/**
	 * call alipay sdk pay. 调用SDK支付
	 * 
	 */
	public void pay() {
		if (TextUtils.isEmpty(PARTNER) || TextUtils.isEmpty(RSA_PRIVATE) || TextUtils.isEmpty(SELLER)) {
			new AlertDialog.Builder(getActivity()).setTitle("警告").setMessage("需要配置PARTNER | RSA_PRIVATE| SELLER")
					.setPositiveButton("确定", new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialoginterface, int i) {
							//
							getActivity().finish();
						}
					}).show();
			return;
		}
		String orderInfo = getOrderInfo("测试的商品", "该测试商品的详细描述", "0.01");

		/**
		 * 特别注意，这里的签名逻辑需要放在服务端，切勿将私钥泄露在代码中！
		 */
		String sign = sign(orderInfo);
		try {
			/**
			 * 仅需对sign 做URL编码
			 */
			sign = URLEncoder.encode(sign, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		/**
		 * 完整的符合支付宝参数规范的订单信息
		 */
		final String payInfo = orderInfo + "&sign=\"" + sign + "\"&" + getSignType();

		Runnable payRunnable = new Runnable() {

			@Override
			public void run() {
				// 构造PayTask 对象
				PayTask alipay = new PayTask(getActivity());
				// 调用支付接口，获取支付结果
				String result = alipay.pay(payInfo, true);
				String version = alipay.getVersion();
				Log.d("TAG", "version: " + version);
				Message msg = new Message();
				msg.what = SDK_PAY_FLAG;
				msg.obj = result;
				mHandler.sendMessage(msg);
			}
		};

		// 必须异步调用
		Thread payThread = new Thread(payRunnable);
		payThread.start();
	}

	/**
	 * get the sdk version. 获取SDK版本号
	 * 
	 */
	public void getSDKVersion() {
		PayTask payTask = new PayTask(getActivity());
		String version = payTask.getVersion();
		Toast.makeText(getActivity(), version, Toast.LENGTH_SHORT).show();
	}

	/**
	 * 原生的H5（手机网页版支付切natvie支付） 【对应页面网页支付按钮】
	 * 
	 * @param v
	 */
	public void h5Pay(View v) {
		Intent intent = new Intent(getActivity(), H5PayDemoActivity.class);
		Bundle extras = new Bundle();
		/**
		 * url是测试的网站，在app内部打开页面是基于webview打开的，demo中的webview是H5PayDemoActivity，
		 * demo中拦截url进行支付的逻辑是在H5PayDemoActivity中shouldOverrideUrlLoading方法实现，
		 * 商户可以根据自己的需求来实现
		 */
		String url = "http://m.meituan.com";
		// url可以是一号店或者美团等第三方的购物wap站点，在该网站的支付过程中，支付宝sdk完成拦截支付
		extras.putString("url", url);
		intent.putExtras(extras);
		startActivity(intent);

	}

	/**
	 * create the order info. 创建订单信息
	 * 
	 */
	private String getOrderInfo(String subject, String body, String price) {

		// 签约合作者身份ID
		String orderInfo = "partner=" + "\"" + PARTNER + "\"";

		// 签约卖家支付宝账号
		orderInfo += "&seller_id=" + "\"" + SELLER + "\"";

		// 商户网站唯一订单号
		orderInfo += "&out_trade_no=" + "\"" + getOutTradeNo() + "\"";

		// 商品名称
		orderInfo += "&subject=" + "\"" + subject + "\"";

		// 商品详情
		orderInfo += "&body=" + "\"" + body + "\"";

		// 商品金额
		orderInfo += "&total_fee=" + "\"" + price + "\"";

		// 服务器异步通知页面路径
		orderInfo += "&notify_url=" + "\"" + "http://notify.msp.hk/notify.htm" + "\"";

		// 服务接口名称， 固定值
		orderInfo += "&service=\"mobile.securitypay.pay\"";

		// 支付类型， 固定值
		orderInfo += "&payment_type=\"1\"";

		// 参数编码， 固定值
		orderInfo += "&_input_charset=\"utf-8\"";

		// 设置未付款交易的超时时间
		// 默认30分钟，一旦超时，该笔交易就会自动被关闭。
		// 取值范围：1m～15d。
		// m-分钟，h-小时，d-天，1c-当天（无论交易何时创建，都在0点关闭）。
		// 该参数数值不接受小数点，如1.5h，可转换为90m。
		orderInfo += "&it_b_pay=\"30m\"";

		// extern_token为经过快登授权获取到的alipay_open_id,带上此参数用户将使用授权的账户进行支付
		// orderInfo += "&extern_token=" + "\"" + extern_token + "\"";

		// 支付宝处理完请求后，当前页面跳转到商户指定页面的路径，可空
		orderInfo += "&return_url=\"m.alipay.com\"";

		// 调用银行卡支付，需配置此参数，参与签名， 固定值 （需要签约《无线银行卡快捷支付》才能使用）
		// orderInfo += "&paymethod=\"expressGateway\"";

		return orderInfo;
	}

	/**
	 * get the out_trade_no for an order. 生成商户订单号，该值在商户端应保持唯一（可自定义格式规范）
	 * 
	 */
	private String getOutTradeNo() {
		SimpleDateFormat format = new SimpleDateFormat("MMddHHmmss", Locale.getDefault());
		Date date = new Date();
		String key = format.format(date);

		Random r = new Random();
		key = key + r.nextInt();
		key = key.substring(0, 15);
		return key;
	}

	/**
	 * sign the order info. 对订单信息进行签名
	 * 
	 * @param content
	 *            待签名订单信息
	 */
	private String sign(String content) {
		return SignUtils.sign(content, RSA_PRIVATE);
	}

	/**
	 * get the sign type we use. 获取签名方式
	 * 
	 */
	private String getSignType() {
		return "sign_type=\"RSA\"";
	}
}
